package website.seamonster.ethegg.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import website.seamonster.ethegg.dataobject.EthUser;
import website.seamonster.ethegg.enums.ResultEnum;
import website.seamonster.ethegg.exception.EthException;
import website.seamonster.ethegg.repository.EthUserRepository;
import website.seamonster.ethegg.utils.PrCodeUtils;

/**
 * Created by 罗海量
 * 2018-08-18 15:59
 */
@lombok.extern.slf4j.Slf4j
@Service
public class EthUserService {
    @Autowired
    private EthUserRepository repository;
    @Autowired
    private MsgService msgService;

    public String getPrCodeByAccountAddress(String address){
        EthUser ethUser = repository.findFirstByEthAddress(address);
        if (ethUser != null) {
            return ethUser.getPrCode();
        } else if (msgService.isUserHasBuyEgg(address)){
            // generate and return
            String newPrCode = null;
            do{
                newPrCode = PrCodeUtils.genPrCode();
            }while(this.getAccountAddressByPrCode(newPrCode)!=null);

            EthUser e = new EthUser();
            e.setEthAddress(address);
            e.setPrCode(newPrCode);
            EthUser ethUserSave = repository.save(e);
            return ethUserSave.getPrCode();
        } else {
            throw new EthException(ResultEnum.PRCODE_NOT_BUY);
        }
    }

    public String getAccountAddressByPrCode(String prCode){
        EthUser user = repository.findFirstByPrCode(prCode);
        if (user == null) {
            return null;
        } else {
            return user.getEthAddress();
        }
    }
}
